package com.example.jimuyutabletcontrol.heartbeatModule;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: HDX
 * @date: 2020\4\7 0007
 */
public abstract class HeartbeatIterface {

    public abstract void startHeartbeat();

    protected List<HeartbeatCallback> heartbeatCallbacks;

    /**
     * 是否停止心跳
     */
    protected boolean isStop = true;

    /**
     * 心跳间隔时间
     */
    protected long heartbeatTime = 1000;

    /**
     * 心跳数目
     */
    protected int heartBeatCount = 0;

    protected boolean threadRunning = false;


    protected HeartbeatIterface() {
        heartbeatCallbacks = new ArrayList<>();
    }

    public int getHeartBeatCount() {
        return heartBeatCount;
    }

    public boolean isStop() {
        return isStop;
    }

    public void setStop(boolean stop) {
        isStop = stop;
    }

    public long getHeartbeatTime() {
        return heartbeatTime;
    }

    public void setHeartbeatTime(long heartbeatTime) {
        this.heartbeatTime = heartbeatTime;
    }

    protected void sendHeartbeat() {
        if (heartbeatCallbacks.size() == 0) return;
        for (HeartbeatCallback callback : heartbeatCallbacks) {
            callback.onHeartbeat();
        }
    }

    public void registerCallback(HeartbeatCallback heartbeatCallback) {
        if (null == heartbeatCallback) return;
        if (heartbeatCallbacks.contains(heartbeatCallback)) return;
        heartbeatCallbacks.add(heartbeatCallback);
    }

    public void removeCallback(HeartbeatCallback heartbeatCallback) {
        if (null == heartbeatCallback) return;
        if (!heartbeatCallbacks.contains(heartbeatCallback)) return;
        heartbeatCallbacks.remove(heartbeatCallback);
    }

    public void removeAllCallback() {
        heartbeatCallbacks.clear();
    }

    /**
     * 停止心跳
     */
    public void stopHeartbeat() {
        isStop = true;
        if (null != heartbeatCallbacks) {
            heartbeatCallbacks.clear();
            heartbeatCallbacks = null;
        }
        heartBeatCount = 0;
    }
}
